<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 输入框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryinfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisble=true">添加按钮</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
               @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
             @click="deleltuser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisble"
      width="50%" @close="addDialogClosed"
    >
     <!-- 内容 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
           <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
           <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
           <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
           <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisble">取 消</el-button>
        <el-button type="primary" @click="addUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 编辑用户的对话框 -->
    <el-dialog
    title="修改用户"
    :visible.sync="editDialogVisible"
    width="50%" @close="editDilogClor">
    <!-- 文字 -->
    <el-form :model="editFrom" :rules="editFormRules" ref="editFormRef" label-width="70px">
     <el-form-item label="用户名">
       <el-input v-model="editFrom.username" disabled></el-input>
     </el-form-item>
     <el-form-item label="邮箱" prop="email">
       <el-input v-model="editFrom.email"></el-input>
     </el-form-item>
     <el-form-item label="电话" prop="mobile">
       <el-input v-model="editFrom.mobile"></el-input>
     </el-form-item>
    </el-form>
    <!-- 底部 -->
    <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editDialogUser">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryinfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 每页显示几条
        pagesize: 2,
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示与颖仓
      addDialogVisble: false,
      // 添加的校验规则
      addFormRules:{
          username:[
               { required: true, message: '请输入活动名称', trigger: 'blur' },
               { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password:[
               { required: true, message: '请输入活动名称', trigger: 'blur' },
               { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
          ],
          email:[
                { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          mobile:[
               { required: true, message: '请输入活动名称', trigger: 'blur' },
               { min: 11, max: 11, message: '长度在11字符', trigger: 'blur' }
          ],
      },
      // 添加用户的表单数据
      addForm:{
          username:'',
          password:'',
          email:'',

      },
      // 控制编辑用户对话框的显示与影藏
      editDialogVisible:false,
      // 查询到的用户信息对象
      editFrom : {},
      // 编辑表单的校验规则
      editFormRules:{
        email:[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { min: 11, max:11, message: '请输入正确手机号', trigger: ['blur', 'change'] }
        ],
      }
    };
  },
  // 生命周期更新阶段
  created() {
    this.getUserList();
  },
  mounted() {},
  methods: {
    // 获取列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryinfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");

      //   获取成功
      this.$message.success("获取用户列表成功");
      this.userList = res.data.users;
      this.total = res.data.total;
      //   console.log(this.userList);
      console.log(res);
    },
    // 监听页码
    handleSizeChange(newsize) {
      // console.log(newsize);
      this.queryinfo.pagesize = newsize;
      this.getUserList();
    },
    // 监听页码值改变的事件 当前显示
    handleCurrentChange(newpage) {
      // console.log(newpage);
      this.queryinfo.pagenum = newpage;
      this.getUserList();
    },
    // 控制开关更新状态
    async userStateChange(userinfo) {
      console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新状态失败");
      }
      this.$message.success("更新状态成功");
    },
    // 监听对话框表单消失
    addDialogClosed() {
        this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加新用户
    addUser() {
        // 验证表单是否成功校验
        this.$refs.addFormRef.validate(async valid => {
            if(!valid) return
            // 发起请求
            const {data:res} = await this.$http.post('users',this.addForm)
            if(res.meta.status !== 201) {
                return this.$message.error('添加用户失败')
            }
           
            this.$message.success('添加用户成功')
            this.addDialogVisble = false
            this.getUserList()
        })
    },
    // 修改用户展示修改用户的对话框
    async showEditDialog(id) {
      const {data:res} = await this.$http.get('users/' + id)
      if(res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.$message.success('获取用户信息成功')
      this.editFrom = res.data
      this.editDialogVisible = true
    },
    // 点击确定修改表单
    editDialogUser() {
      // 完成修改之前的表单验证
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid);
        if(!valid) return
         // 发送请求
         const {data:res} = await this.$http.put('users/' + this.editFrom.id,{
           email:this.editFrom.email,
           mobile:this.editFrom.mobile
         })
         if(res.meta.status !== 200) {
           return this.$message.error('更新用户信息失败')
         }
         this.$message.success('更新用户信息成功')
         // 关闭对话框
         this.editDialogVisible = false
         // 重新渲染页面
         this.getUserList()
      })
     
    },
    // 监听修改用户对话框的关闭事件
    editDilogClor() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除用户对话框
   async deleltuser(id) {
     // 弹框提示用户
        const fonfirmbut =  await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if(fonfirmbut !== 'confirm') {
          return this.$message.info('已取消修改')
        }
         console.log('确认了删除');
        const {data:res} = await this.$http.delete('users/' + id) 
        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('删除用户成功')
        // 重新渲染页面
        this.getUserList()
    }

  },
};
</script>

<style scoped lang="less">
</style>
